from urllib2 import urlopen, HTTPError
from BeautifulSoup import BeautifulStoneSoup
from galleries import Gallery

class Parade():
	def __init__(self,user=None):
		self.user = user
		self._galleries = []
		
	@property
	def galleries(self):
		if not self._galleries:
			try:
				xml = urlopen('http://api.paradepro.com/1.0/users/%s/galleries.xml' % self.user).read()
			except HTTPError:
				raise Exception('XML file not found - are you sure the username is correct?')
			galleries_xml = BeautifulStoneSoup(xml,selfClosingTags=['gallery'])
			for gallery in galleries_xml.findAll(name='gallery'):
				self._galleries.append(Gallery(gallery._getAttrMap()))
		return self._galleries
		
	def get_galleries(self):
		try:
			xml = urlopen('http://api.paradepro.com/1.0/users/%s/galleries.xml' % self.user).read()
		except HTTPError:
			raise Exception('XML file not found - are you sure the username is correct?')
		galleries_xml = BeautifulStoneSoup(xml,selfClosingTags=['gallery'])
		for gallery in galleries_xml.findAll(name='gallery'):
			self.galleries.append(Gallery(gallery._getAttrMap()))
		return self.galleries
	def get_gallery(self,slug):
		try:
			xml = urlopen('http://api.paradepro.com/1.0/users/%s/galleries/%s.xml' % (self.user,slug)).read()
		except HTTPError:
			raise Exception('Gallery not found - are you sure the username/slug is correct?')
		gallery_xml = BeautifulStoneSoup(xml,selfClosingTags=['photo'])
		
		return gallery_xml.findAll(name='photo')